package com.xz.disk.utils;

//import de.hunsicker.jalopy.Jalopy;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

import static java.lang.System.out;

/**
 * @program: jdbc
 * @description: 文件操作工具类
 * @author: Shawn
 * @create: 2019-11-20 15:24
 **/
public class FileUtil {


    // 预览图片
    public static void lookImages(String path, HttpServletResponse response) {
        File file = null;
        FileInputStream fis = null;
        try {
            file = new File(path);
            if(!file.exists()){
                return;
            }
            fis = new FileInputStream(file);
            final byte[] buf = new byte[1024];
            while (fis.read(buf)>0){
                response.getOutputStream().write(buf);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    fis=null;
                }
            }
        }
    }


    /**
     * @Description: 把生成的java代码，按照java格式格式化
     * @Param: 内容字符串，文件名
     * @return: 格式化后的字符串
     * @Author: Shawn
     * @Date: 2019/11/20 - 15:25
     */
//    public static String javaFormat(String str, String fileName) {
//        StringBuffer output = new StringBuffer();
//        Jalopy j = new Jalopy();
//        j.setEncoding("UTF-8");
//        j.setInput(str, fileName + ".java"); // 第二个参数随便填个java类名
//        j.setOutput(output);
//        j.format();
//        return output.toString();
//    }

    // 上传到当前文件夹
    public static String uploadFile(MultipartFile file, String path) {
        try {
            String oldName = file.getOriginalFilename();
//            String newName = System.currentTimeMillis() + oldName;
            file.transferTo(new File(path +oldName));
            out.println("<<<<<<<<<<【\t"+path + oldName+"\t】>>>>>>>>>>>>");
            return oldName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String uploadEditorImage(MultipartFile file, String path) {
        try {
            String oldName = file.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            String newName = System.currentTimeMillis()+suffix;
            file.transferTo(new File(path +newName));
            out.println("<<<<<<<<<<【\t"+path + newName+"\t】>>>>>>>>>>>>");
            return newName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Description: 判断地址是否存在
     * @Param: 地址
     * @return: 是/否
     * @Author: Shawn
     * @Date: 2019/11/20 - 15:27
     */
    public static boolean exist(String path) {
        return new File(path).exists();
    }

    /**
     * @Description: 创建文件夹
     * @Param: 地址
     * @return: 是/否 成功
     * @Author: Shawn
     * @Date: 2019/11/20 - 15:29
     */
    public static boolean mkdir(String path) {
        try {
            new File(path).mkdir();
            out.println("====>>>\t文件夹"+path+"创建成功");
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        out.println("====>>>\t文件夹"+path+"创建成功");
        return false;
    }

    /**
     * @Description: 创建文件
     * @Param: 地址
     * @return: 是/否 成功
     * @Author: Shawn
     * @Date: 2019/11/20 - 15:32
     */
    public static boolean touch(String path) {
        try {
            new File(path).createNewFile();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @Description: 把 电脑合成的语音 保存 mp3文件
     * @Author: Shawn
     * @Date: 2019/12/6 - 15:18
     */
    public static String[] saveMP3(byte[] data) {
        String fileName = System.currentTimeMillis() + "answer.mp3";
        String path = System.getProperty("user.dir") + File.separator + "audio" + File.separator + fileName;
        if (FileUtil.exist(path)) {
            FileUtil.touch(path);
            System.err.println("文件创建成功\t" + path);
        }
        OutputStream os = null;
        FileOutputStream fos = null;
        try {
            os = new FileOutputStream(new File(path));
            os.write(data);
            return new String[]{path, fileName};
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static byte[] readFileToByte(String path) {
        try {
            File file = new File(path);
            long fileSize = file.length();
            if (fileSize > Integer.MAX_VALUE) {
                out.println("file too big...");
                return null;
            }
            FileInputStream fi = new FileInputStream(file);
            byte[] buffer = new byte[(int) fileSize];
            int offset = 0;
            int numRead = 0;
            while (offset < buffer.length
                    && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
                offset += numRead;
            }
            // 确保所有数据均被读取
            if (offset != buffer.length) {
                throw new IOException("Could not completely read file "
                        + file.getName());
            }
            fi.close();
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @Description: 开启线程异步延迟删除文件
     * @Author: Shawn
     * @Date: 2019/12/6 - 15:27
     */
    public static void pendMove(String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(180000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                out.println(new File(path).delete() ? "删除文件成功\t" + path : "删除失败\t" + path);
            }
        }).start();
    }


    /**
     * @Description: 在文件写入内容
     * @Param: 地址、内容
     * @return: 是/否 成功
     * @Author: Shawn
     * @Date: 2019/11/20 - 15:35
     */
    public static boolean writeFile(String path, String content) {
        OutputStream os = null;
        FileOutputStream fos = null;
        try {
            os = new FileOutputStream(new File(path));
            os.write(content.getBytes());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }


    /**
     * @Description: 读取指定路径文件的内容
     * @Param: 地址
     * @return: 内容
     * @Author: Shawn
     * @Date: 2019/11/20 - 17:42
     */
    public static String readFile(String path) {
        if (!exist(path)) {
            System.err.println("要读取的文件路径不存在");
            return null;
        }
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            is = new FileInputStream(new File(path));
            isr = new InputStreamReader(is, "UTF-8");
            int len;
            StringBuffer sbf = new StringBuffer();
            while ((len = isr.read()) != -1) {
                sbf.append((char) len);
            }
            return sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @Description: 首字母大写
     * @Param: 字符串
     * @return: 首字母大写后的字符串
     * @Author: Shawn
     * @Date: 2019/11/20 - 16:19
     */
    public static String firstToUpperCase(String str) {
        String s = str.substring(0, 1).toUpperCase();
        return s + str.substring(1);
    }

    /**
     * @Description: 首字母小写
     * @Param: 字符串
     * @return: 首字母小写后的字符串
     * @Author: Shawn
     * @Date: 2019/11/20 - 16:19
     */
    public static String firstToLowerCase(String str) {
        String s = str.substring(0, 1).toLowerCase();
        return s + str.substring(1);
    }




    /**
     * @Description: 递归下一层，删除文件
     * @Author: Shawn
     * @Date: 2019/12/6 - 15:05
     */
    public static boolean deleteAll(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if(files!=null && files.length>0){
            for(File f : files){
                f.delete();
            }
        }
        return file.delete();
    }

    public static boolean delete(String path){
        return new File(path).delete();
    }

    public static void main(String[] args) {
//        String s = "E:\\aaaa\\新建文件夹\\123456789.png";
//        out.println("====>>>\t"+s.lastIndexOf(File.separator));
//
//        String prefix = s.substring(0,s.lastIndexOf(File.separator));
//        String suffix = s.substring(s.lastIndexOf(File.separator));
//        out.println("====>>>\t"+prefix);
//        out.println("====>>>\t"+suffix);
//        move("C:\\Users\\ASUS\\Desktop\\move","C:\\Users\\ASUS\\Desktop\\move2");

    }

    public static boolean isDirectory(String path){
        return new File(path).isDirectory();
    }

    public static boolean rename(String path,String newName){
        File file = new File(path);
        String prefix = path.substring(0,path.lastIndexOf(File.separator)+1);
        return file.renameTo(new File(prefix+newName));
    }

    // 移动文件夹
    public static boolean move(String oldPath,String newPath){
        if(FileUtil.exist(newPath)){
            return false;
        }
        try {
            if(isDirectory(oldPath)){
                FileUtils.moveDirectory(new File(oldPath), new File(newPath));
            }else{
                FileUtils.moveFile(new File(oldPath), new File(newPath.trim()));
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

}
